// App Root
var appPath = getAppPath();

// 是否延迟加载
var lazy = false;

// Datagrid ID
var datagrid_id = "#acquGrid";

// Datagrid URL参数
var datagrid_url = appPath+'/acqu/rule_list.do';

// Dialog ID
var dialog_id = "#addAcquDlg";

// Form ID
var form_id = "#addAcquForm";

/**
 * jQuery加载事件
 */
$(function(){
	// 初始化Datagrid
	initPlugin();
	$("#categoryId").combobox({url:appPath+'/info/category_listCombo.do',valueField:'categoryId',textField:'categoryName'});
	
	$("#linksetType").combobox({
		onSelect: function(param) {
			switch (param.value) {
			case "3":
				$("#set_plot_1").hide();
				$("#set_plot_3").show();
				
				if ($("#linksetSelector").val().length < 1) {
					$("#linksetSelector").val(" ");
				}
				
				if ($.trim($("#linksetStart").val()).length < 1) {
					$("#linksetStart").val("");
				}
				if ($.trim($("#linksetEnd").val()).length < 1) {
					$("#linksetEnd").val("")
				}
				break;
			default:
				$("#set_plot_1").show();
				$("#set_plot_3").hide();
				
				if ($("#linksetStart").val().length < 1) {
					$("#linksetStart").val(" ");
				}
				if ($("#linksetEnd").val().length < 1) {
					$("#linksetEnd").val(" ")
				}
				
				if ($.trim($("#linksetSelector").val()).length < 1) {
					$("#linksetSelector").val("");
				}
				break;
			}
		}
	});
	
	$("#contentType").combobox({
		onSelect: function(param) {
			switch (param.value) {
			case "3":
				$("#content_plot_1").hide();
				$("#content_plot_3").show();
				
				if ($("#contentSelector").val().length < 1) {
					$("#contentSelector").val(" ");
				}
				
				if ($.trim($("#contentStart").val()).length < 1) {
					$("#contentStart").val("");
				}
				if ($.trim($("#contentEnd").val()).length < 1) {
					$("#contentEnd").val("")
				}
				break;
			default:
				$("#content_plot_1").show();
				$("#content_plot_3").hide();
				
				if ($("#contentStart").val().length < 1) {
					$("#contentStart").val(" ");
				}
				if ($("#contentEnd").val().length < 1) {
					$("#contentEnd").val(" ")
				}
				
				if ($.trim($("#contentSelector").val()).length < 1) {
					$("#contentSelector").val("");
				}
				break;
			}
		}
	});
});

/**
 * 控件初始化方法
 */
function initPlugin() {
	$(datagrid_id).datagrid({
		url: lazy? '' : datagrid_url,
		height: "full",
		striped: true,
		remoteSort:false,
		queryParams: getQueryParam(),
		idField:'acquisitionId',
		checkbox:true,
		frozenColumns:[[
		      {field:'ck',checkbox:true},
		      {field:'ceditor',title:'操作',width:40,align:'center',
		    	  formatter:function(value,rowData,rowIndex){
		    	  	  // var dataStr = JSON.stringify(rowData);
		    		  return "<a href='javascript:void(0)'><img border='0' width='12px' height='12px'  src='"+appPath+"/js/lib/jquery-easyui/themes/icons/pencil.png' title='编辑' onClick='showEdit("+rowIndex+")'/></a>";
		    	  }
		      }
		]],
		columns:[[
		      {field:'acqName',title:'采集名称',width:160,align:'left'},
		      {field:'status',title:'状态',width:50,align:'center',
		    	  formatter:function(value,rowData){
		    		  return value != 1? rowData.statusName : "<span style=\"color:red\"><b>" + rowData.statusName + "</b></span>";
		    	  }
		      },
		      {field:'pauseTime',title:'间隔时长(ms)',width:80,align:'center'},
		      {field:'startTime',title:'开始时间',width:130,align:'center',
		    	  formatter:function(value,rowData){
		    		  var s_date = value != null? $.DateUtil.format(new Date(value),'yyyy-MM-dd hh:mm:ss') : '';
		    		  return s_date;
		    	  }
		      },
		      {field:'endTime',title:'结束时间',width:130,align:'center',
		    	  formatter:function(value,rowData){
		    		  var e_date = value != null? $.DateUtil.format(new Date(value),'yyyy-MM-dd hh:mm:ss') : '';
		    		  return e_date;
		    	  }
		      },
		      {field:'acquisitionId',title:'控制区',width:160,align:'center',
		    	  formatter:function(value,rowData,rowIndex){
		    	  	  // var dataStr = JSON.stringify(rowData);
		    		  var s_btn = '<a href="'+appPath+'/acqu/control_start.do?multi_id='+value+'" onclick="javascript: $.loading(true);">开始</a>';
		    		  var p_btn = '<a href="'+appPath+'/acqu/control_pause.do?multi_id='+value+'" onclick="javascript: $.loading(true);">暂停</a>';
		    		  var e_btn = '<a href="'+appPath+'/acqu/control_stop.do?multi_id='+value+'" onclick="javascript: $.loading(true);">停止</a>';
		    		  var c_btn = '<a href="'+appPath+'/acqu/control_cancel.do?multi_id='+value+'" onclick="javascript: $.loading(true);">取消</a>';
		    		  var split = " | ";
		    		  
		    		  var btns = "";
		    		  if (rowData.status == 0 || rowData.status == 2) { // 停止与暂停状态
		    			  btns = s_btn + split + "暂停 " + split + "停止";
		    			  if (rowData.queue > 0) { // 待运行状态
		    				  btns = '<font style="color: red;">待运行('+rowData.queue+')</font>' + split + c_btn;
		    			  }
		    		  } else if (rowData.status == 1) { // 运行状态 
		    			  btns = "开始 " + split + p_btn + split + e_btn;
		    		  }		    		
		    		  return btns;
		    	  }
		      }
		 ]],
		 pagination:true,
		 rownumbers:true,
		 onLoadSuccess: function() {
			 uncheckAll(this);
			 changeTipInfo("tommy-cell");
		 },
		 toolbar:[{
				id:'btnadd',
				text:'增加',
				iconCls:'icon-add',
				handler:function(){
					showAdd();
				}
			},'-',{
				id:'btndelMu',
				text:'删除',
				iconCls:'icon-cancel',
				handler:function(){
					var selections = $(datagrid_id).datagrid('getSelections');
					if(selections == null || selections == ''){
						$.messager.alert('提示信息','请选择要删除的数据','info');
						return ;
					}else{
						$.messager.confirm('提示信息','您确定要删除这些记录？',function(r){
							if(r){
								var ids = '';
								for(var i=0;i<selections.length;i++){
									ids += selections[i].acquisitionId+',';
								}
								ids = ids.substring(0,ids.lastIndexOf(','));
								
								$.loading(true);
								$.ajax({
									url:appPath+'/acqu/rule_delMulti.do',
									data:{multi_id:ids},
									success:function(data){
										$.loading(false);
										if(data!='ok'){
											$.messager.alert('提示信息','采集有相关联的历史记录，不能删除！','info');
										}else{
											doReload('delete');
										}
									},
									error:function(XMLHttpRequest, textStatus, errorThrown){
										$.loading(false);
										$.messager.alert('提示信息','抱歉，删除未能完成，'+textStatus,'error');
									}
								});		
							}
						});
					}
				}
			},'-',{
				id:'btncreeper',
				text:'开始采集',
				iconCls:'icon-search',
				handler:function(){
					var selections = $(datagrid_id).datagrid('getSelections');
					if(selections == null || selections == ''){
						$.messager.alert('提示信息','请选择要开始的采集','info');
						return ;
					}else{
						var ids = '';
						for(var i=0;i<selections.length;i++){
							ids += selections[i].acquisitionId+',';
						}
						ids = ids.substring(0,ids.lastIndexOf(','));
						window.location.replace(appPath+'/acqu/control_start.do?multi_id=' + ids);
						$.loading(true);
					}
				}
			}]
	});
	if (lazy)
		$(datagrid_id).datagrid('options').url = datagrid_url;
}

/**
 * 控件展现方法
 */
function showPlugin() {
	if (lazy) {
		initPlugin();
		lazy = false;
	}		
}

/**
 * 展现编辑采集
 * @param {} rowData
 */
function showEdit(rowIndex){
	var rowData = $(datagrid_id).datagrid("getRows")[rowIndex];
	$(form_id).form('clear');
	$("#linksetType").combobox("select", rowData.linksetType);
	$("#contentType").combobox("select", rowData.contentType);
	$(form_id).form('load',rowData);
	
	$("#submitType").val("update");
	$(dialog_id).window({
			title:'编辑数据采集',
			iconCls:'icon-edit',
			modal: true,
			shadow: true,
			collapsible:false,
			minimizable:false,
			maximizable:false
		});	
	$(dialog_id).window('move',{top:80});
	$(dialog_id).window('open');	
}

/**
 * 提交数据（包括增加，修改）
 */
function doPostData(){
	$("#acqName").val($.trim($("#acqName").val()));
	
	if(!$(form_id).form('validate')){
		return ;
	}
	var type = $("#submitType").val();
	var typeStr = "";
	if(type == "save"){
		typeStr = "保存";
	}else if(type == "update"){
		typeStr = "更新";
	}
	
	var subData = $(form_id);  
    var acqu = subData.serialize();
    $.loading(true);
    if (type == "save") {
    	ajaxPostData(type, acqu);
    } else {
    	ajaxPostData(type, acqu);
    }
}

function ajaxPostData(type, acqu) {
	$.ajax({
		url:appPath+'/acqu/rule_'+type + '.do',
		type:"post",
		data:acqu,
		success:function(data){
			$.loading(false);
			if(data == "error"){
				$.messager.alert('提示信息','该采集名称已存在，请更换其它！','info');
			}else{
				doReload(type);
				closeWindow();
			}
		},
		error:function(XMLHttpRequest, textStatus, errorThrown){
			$.loading(false);
			$.messager.alert('提示信息','抱歉，'+typeStr+'未能完成，'+textStatus,'error');
		}
	});
}

/**
 * 关闭对话框
 */
function closeWindow(){
	$(dialog_id).window('close');
}

/**
 * 展现增加采集
 */
function showAdd(){
	$(form_id).form('clear');
	$("#submitType").val("save");
	$("#pageEncoding").val("GBK");
	$("#linksetType").combobox("select", "1");
	$("#contentType").combobox("select", "1");
	$(form_id).form('validate');
	
	$(dialog_id).window({
		title:'增加数据采集',
		iconCls:'icon-add',
		modal: true,
		shadow: true,
		collapsible:false,
		minimizable:false,
		maximizable:false
	});
	
	$(dialog_id).window('move',{top:80});
	$(dialog_id).window('open');
}

/**
 * 获取请求信息
 * @return {}
 */
function getQueryParam(){
	var submitObject = new Object();
	return submitObject;
}

/**
 * 查询数据
 */
function doQuery(){
	showPlugin();
	$(datagrid_id).datagrid('unselectAll');
	$(datagrid_id).datagrid('load',getQueryParam());
}

/**
 * 重载grid，取消全选
 */
function doReload(type){
	var ops = $(datagrid_id).datagrid('getPager').pagination("options");
	if(type == "save"){
		var pn = Math.floor(ops.total/ops.pageSize)+1;
		$(datagrid_id).datagrid('getPager').pagination({pageNumber:pn});
		$(datagrid_id).datagrid('options').pageNumber = pn;
	}else if(type == "delete"){
		if($(datagrid_id).datagrid('getRows').length == $(datagrid_id).datagrid('getSelections').length){
			var pn ;
			var pnt = Math.ceil(ops.total/ops.pageSize);
			var pm = ops.pageNumber;
			if(pnt == (pm-1)){
				pn = pnt ;
			}else{
				pn = pm
			}
			$(datagrid_id).datagrid('getPager').pagination({pageNumber:(pn==0?1:pn)});
			$(datagrid_id).datagrid('options').pageNumber = (pn==0?1:pn);
		}
	}
	$(datagrid_id).datagrid('unselectAll');
	$(datagrid_id).datagrid('reload');
}
